12. Lab II: Solution

Solution: Build a Dog GraphQL API - Schema

Below, we'll walk through each step of the lab and look at one potential way to implement the lab. Even if you get stuck, you should always first try to work through the lab without the solution before coming here, so that you can best learn the related skills and be ready for the project at the end of the course.

Step 1: Create an entity called Dog.

  • The dog should have three attributes:
    • Name
    • Breed
    • Origin

You can re-use your code from the REST API for the Dog entity, just make sure to update the package name accordingly!

Step 2: Create a GraphQL schema.

  • The schema should match the fields found in the Dog entity.
  • Add the following query operations:
    • findDogBreeds
    • findDogBreedById
    • findAllDogNames
  • Add the following mutators:
    • deleteDogBreed
    • updateDogName

Following the video, create a graphql package within the resources directory of the project. Within that package, add a dog.graphqls file (you can add as a text file in IntelliJ if you do not have the GraphQL plug-in yet).

type Dog {
    id: ID!
    name: String!
    breed: String!
    origin: String!
}

type Query {
    findAllDogs: [Dog]!
    findDogById(id:ID!): Dog!
}

type Mutation {
    deleteDogBreed(breed:String!) : Boolean
    updateDogName(newName: String!, id:ID!) : Dog!
}

Now, you may be thinking I did not actually implement the query operations that were requested. But wait - using GraphQL, the user will be able to specify which fields they want from a query. So, simply by adding the queries for find all dogs (where they can request only breed, or only names), and finding a dog by id (where they can request just the breed), these operations actually exist.

Step 3: Create a repository that extends CrudRepository.

  • This repository is for creating, reading, updating, and deleting Dog objects.

Depending on how you implemented your DogRepository for the REST API, you may be able to completely re-use your code here. I actually chose to completely remove any queries from within the DogRepository, as there are already built-in methods for a CrudRepository that findAll and findById.

package com.udacity.DogGraphQL.repository;

import com.udacity.DogGraphQL.entity.Dog;
import org.springframework.data.repository.CrudRepository;

public interface DogRepository extends CrudRepository<Dog, Long> {
}

What about the service and controller?

We don't need these to implement a GraphQL API. If you still want to have a REST API available, you can add those files to the application as well, and the same endpoints as before will be available.